package com.ipay;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：前世小和尚（xiaopingzhang8@creditease.cn）
 * @Description ：
 * @ClassName ：URLFildder
 * @Company ：普信恒业科技发展（北京）有限公司
 * @date ：2018/4/12 19:01
 */
public class URLFildder {
    public static void main(String[] args) throws Exception {
        String url = "https://mp.weixin.qq.com/s/AKRaZPxK4aI_FxmYkGgVRg";
        URL u = new URL(url);
        InputStreamReader in = new InputStreamReader(u.openStream());
        BufferedReader reader = new BufferedReader(in);
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        System.out.println(content.toString());
        String title = getTitle(content);
        System.out.println("title-" + title);

        String image = getImage(content);
        System.out.println("result-" + image);
    }

    private static String getImage(StringBuilder content) {
        String regex = "<img.*?>";
        List<String> images = new ArrayList<>();
        StringBuilder sbImages = new StringBuilder();
        Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
        Matcher ma = pa.matcher(content);
        while (ma.find()) {
            sbImages.append(ma.group() + "\r\n");
        }
        //根据正则筛选图片
        return boltImage(sbImages);
    }

    /**
     * 筛选图片
     *
     * @param images
     * @return
     */
    private static String boltImage(StringBuilder images) {
        String regex = "<img .*data-w=\"[1-9]{3,4}.*?>";
        Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
        Matcher ma = pa.matcher(images);
        String im;
        while (ma.find()) {
            if ((im = firstImage(ma.group())) != null && im.length() > 0) {
                return im;
            }
        }
        return null;

    }

    private static String firstImage(String src) {
        String regex = "data-src=\".*?\"";
        Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
        Matcher ma = pa.matcher(src);
        if (ma.find()) {
            return ma.group().replaceAll("data-src=\"", "").replaceAll("\"", "");
        }
        return null;
    }

    /**
     * 获取文章标题
     *
     * @param content
     * @return
     */
    private static String getTitle(StringBuilder content) {
        String regex;
        String title = "";
        regex = "<title>.*?</title>";
        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
        final Matcher ma = pa.matcher(content);
        if (ma.find()) {
            title = ma.group();
        }
        title = title.replaceAll("<.*?>", "");
        return title;
    }
}
